package day01;

/**
 * 双向链表
 * @param <E> 元素的类型
 */
public class MyLinkedList<E> {
    private int size = 0;
    private Node<E> first;
    private Node<E> last;

    private static class Node<E>{
        E item;
        Node<E> next;
        Node<E> prev;
        public Node(E e){
            item = e;
        }
    }

    /**
     * 将元素e添加到集合中
     * @param e 被添加的元素
     * @return true表示添加成功
     */
    public boolean add(E e){
        if (size==0) {
            Node<E> node = new Node<>(e);
            first = node;
            last = node;
        }else{
            Node<E> node = new Node<>(e);
            last.next = node;
            node.prev = last;
            last = node;
        }
        size++;
        return true;
    }

    public E get(int index){
        if (index <0 || index >= size){
            throw new IndexOutOfBoundsException("超过范围!");
        }
        //找到插入位置
        Node<E> node = find(index);
        return node.item;
    }
    private Node<E> find(int index){
        //找到插入位置
        Node<E> node;
        if (index < size >> 1) {
            System.out.println("从头找");
            node = first;
            for (int i = 0; i < index; i++) {
                node = node.next;
            }
        }else{
            System.out.println("从尾找");
            node = last;
            for (int i=size-1; i>index ;i--){
                node = node.prev;
            }
        }
        System.out.println("找到:"+node.item);
        return node;
    }

    public E delete(int index){
        return null;
    }

    public int size(){
        return size;
    }

    @Override
    public String toString() {
        return "";
    }

    public boolean add(int index, E e){
        if (index<0 || index>size){
            throw new IndexOutOfBoundsException("越界");
        }
        if (index == size){ //尾部追加
            return add(e);
        }
        if (index == 0){ //头部插入
            Node<E> newNode = new Node<>(e);
            first.prev = newNode;
            newNode.next = first;
            first = newNode;
            size++;
            return true;
        }
        Node<E> newNode = new Node<>(e);
        //找到插入位置
        Node<E> node = find(index);
        Node<E> prev = node.prev; //找到前一个节点
        prev.next = newNode;  //将新节点编入链表
        newNode.next = node;
        node.prev = newNode;
        newNode.prev = prev;
        size++;
        return true;
    }
}
